/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.session.web;

import io.iec.edp.caf.boot.security.CAFSecurityWebSessionHolder;
import io.iec.edp.caf.commons.core.SerializerFactory;
import io.iec.edp.caf.commons.core.enums.SerializeType;
import io.iec.edp.caf.core.session.CafSession;
import io.iec.edp.caf.core.session.CafSessionHolder;
import io.iec.edp.caf.core.session.SessionType;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangyandong
 */
@Slf4j
public class WebSessionHolder implements CafSessionHolder {
    /**
     * 返回匹配的Session类型
     */
    @Override
    public List<SessionType> getMatchingSessionTypes() {
        List<SessionType> list = new ArrayList<>();
        list.add(SessionType.web);
        list.add(SessionType.mobile);
        return list;
    }

    /**
     * 获取当前的Session对象
     */
    @Override
    public CafSession getCurrentSession() {
        var session = CafWebSessionThreadLocal.getCurrentSession();
        if (session == null) {
            session = CAFSecurityWebSessionHolder.getCafSession();
        }
        return session;
//        return CAFSecurityWebSessionHolder.getCafSession();
    }

    @Override
    public CafSession getCopyedCurrentSession() {
        var session = CafWebSessionThreadLocal.getCurrentSession();
        if (session == null) {
            session = CAFSecurityWebSessionHolder.getCafSession();
        }
        if (session == null) {
            return null;
        }

        var serializer = SerializerFactory.getSerializer(SerializeType.Json);
        var deserializer = SerializerFactory.getDeserializer(SerializeType.Json);

        return deserializer.deserialize(serializer.serializeToString(session), CafSession.class);
    }

    /**
     * 获取当前的Session对象
     */
    @Override
    public void setCurrentSession(CafSession session) {
        if (log.isDebugEnabled()) {
            log.debug("设置web session，ThreadName={}，sessionId={}", Thread.currentThread().getName(),
                    session != null ? session.getId() : null, new Exception());
        }

        SecurityContextHolder.getContext().setAuthentication(session);
    }

    @Override
    public void setCurrentThreadPoolSession(CafSession session) {
        if (log.isDebugEnabled()) {
            log.debug("设置web ThreadPool session，ThreadName={}，sessionId={}", Thread.currentThread().getName(),
                    session != null ? session.getId() : null, new Exception());
        }

        CafWebSessionThreadLocal.setCurrentSession(session);
    }

    /**
     * 清理当前Session
     */
    @Override
    public void clear() {
        if (log.isDebugEnabled()) {
            CafSession currentSession = null;
            try {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if (authentication instanceof CafSession) {
                    currentSession = (CafSession) authentication;
                }
            } catch (Exception e) {
            }
            log.debug("清理web session，ThreadName={}，sessionId={}", Thread.currentThread().getName(),
                    currentSession != null ? currentSession.getId() : null, new Exception());
        }

        SecurityContextHolder.clearContext();
    }

    @Override
    public void clearCurrentThreadPoolSession() {
        if (log.isDebugEnabled()) {
            CafSession currentSession = CafWebSessionThreadLocal.getCurrentSession();
            log.debug("清理web ThreadPool session，ThreadName={}，sessionId={}", Thread.currentThread().getName(),
                    currentSession != null ? currentSession.getId() : null, new Exception());
        }

        CafWebSessionThreadLocal.purge();
    }
}
